<template>
    <div class="app-image-upload"> 
        <van-row class="app-image-upload-label">
            <van-col span="8"  style="text-align: left;">
                <span class="stars" style="color: red;" v-if="!allowEmpty">*</span>
                {{labelText}}
            </van-col>
            <van-col span="16">
              <van-uploader :after-read="afterRead" :before-read="beforeRead" @oversize="oversize" :max-size="maxSize" :disabled="disabled">
                <van-icon name="photo" />
            </van-uploader>
            </van-col>
        </van-row>
          <div class="app-image-list">
              <span v-for="item in fileList" :key="item.id"  class="app-image-list-item">
              <img :src="exportImageUrl+item.id" class="app-image-list-item-image"/>
               <span class="app-file-upload-tag-close" @click="deleteImg(item)"><van-icon name="cross" /></span>
              </span>
          </div> 
    </div>
</template>



<script lang="ts">
import { Vue, Component, Prop, Provide, Emit, Watch } from 'vue-property-decorator';
import {Environment} from '@/environments/environment';
import axios from 'axios'
import { Toast } from 'vant'

@Component({
    components: {
      
    }
})
export default class AppImageUpload extends Vue {
    
        /**
        * 父组件传递过来的image
        * 
        * @type {Array<any>}
        * @memberof AppImageUpload
        **/
        @Prop() public value?:any;

        /**
        * 是否允许为空
        * 
        * @type {boolean}
        * @memberof AppImageUpload
        **/
        @Prop() public allowEmpty!:boolean;

        /**
         * labelText
         *
         * @type {string}
         * @memberof AppImageUpload
         */
        @Prop() public labelText!:string;

        /**
         * 是否禁用
         *
         * @type {boolean}
         * @memberof AppImageUpload
         */
        @Prop() public disabled?:boolean;

        /**
         * 监听value值变化
         *
         * @memberof AppUploadFile
         */
        @Watch('value', { immediate: true, deep: true })
        onValueChanged(val: any, oldVal: any) {
            if(val && JSON.parse(val).length >0){
                this.fileList = JSON.parse(val);
            }else{
                this.fileList = [];
            }
        }

        
        /**
        * 文件最大大小
        *
        * @type {any}
        * @memberof AppImageUpload
        **/
        public maxSize:number=5*1024*1024;

        /**
        * 导出路径
        *
        * @type {any}
        * @memberof AppImageUpload
        **/
        public exportImageUrl:string=Environment.BaseUrl+Environment.ExportFile+'/';

        /**
        * 图片列表
        * 
        * @type {Array<any>}
        * @memberof AppImageUpload
        **/
        public fileList:Array<any> = []

        /**
        *  组件抛出值
        *  @param {*} val
        *  @memberof AppUploadFile
        **/
        public emitValue(val:any){
            this.$emit('valuechange',JSON.stringify(val));
        }

        /**
         * 删除图片时调用
         *
         * @type {file}
         * @memberof AppImageUpload
         */
        public deleteImg(file:any){
            this.fileList = [];
            this.emitValue(this.fileList);
        }
        
        /**
         * 上传之前校验
         *
         * @type {file}
         * @memberof AppImageUpload
         */
        public beforeRead(file:any) {
          let patt=/image/;
          if (!patt.test(file.type)) {
            Toast("请选择图片");
            return false;
          }else{
              if(this.fileList.length >0){
                  Toast("最多选择一张图片");
                  return false;
              }else{
                  return true;
              }
          }
        }
        
        /**
         * 上传文件超过最大限制调用
         *
         * @type {file}
         * @memberof AppImageUpload
         */
        public oversize(file:any){
          Toast("图片过大,上传失败")
        }

        /**
         * 已读后上传
         *
         * @type {file}
         * @memberof AppImageUpload
         */
        public afterRead(file:any){ 
            this.upLoaderImg(file.file);
         
        }


        /**
         * 上传图片
         *
         * @memberof AppImageUpload
        */
        public upLoaderImg (file:any) {	
              let params = new FormData()
              params.append('file', file)
              let config = {
                    headers: { //添加请求头
                        'Content-Type': 'multipart/form-data'
                    }
                }
                axios.post(Environment.BaseUrl+Environment.UploadFile ,params, config).then(res => {
                      if (res && res.data && res.status === 200) {	
                        this.fileList =[];
                        this.fileList.push(res.data);
                        this.emitValue(this.fileList);
                        Toast('上传成功');                    
                      } else {
                        Toast('上传失败');
                      }
                    }).catch(err => {
                        Toast('上传失败');
                  });
        }

    }
</script>
<style lang="less">
.app-image-upload {
  .app-image-upload-label {
    display: flex;
    align-items: center;
    justify-content: space-between;
       .van-icon {
        position: relative;
        font: 14px/1 "vant-icon";
        font-size: inherit;
        font-size: 20px;
        text-rendering: auto;
        -webkit-font-smoothing: antialiased;
        margin-top: 10px;
    }
  }
  .app-image-list{
    display: flex;
    justify-content: space-between;
    align-items: center;
      .app-image-list-item{
          position: relative;
          .app-image-list-item-image{
              max-width:100px;
              max-height:80px;
          }
          .app-file-upload-tag-close{
                position: absolute;
                top: 0;
                right: 0;
          }
      }
  }
}
    
</style>